package de.gzork.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.gzork.client.FBException;
import de.gzork.client.GzorkService;
import de.gzork.zmpp.ZmppWrapper;
import de.gzork.zmpp.ZmppWrapperFactory;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GzorkServiceImpl extends RemoteServiceServlet implements GzorkService {

	private FacebookHelper _helper;

	public FacebookHelper getHelper() {
		if (_helper == null) {
			_helper = new FacebookHelper(getThreadLocalRequest(), getThreadLocalResponse());
		}
		return _helper;
	}

	@Override
	public String greetServer(String name, String command) {
		String result = "";
		name = getHelper().getUserID() + "";
		System.out.println("**** GREET ****");

		ZmppWrapper zmpp = null;

		if (getServletContext().getAttribute(name) == null) {
			zmpp = ZmppWrapperFactory.createMiniZork(name);
			getServletContext().setAttribute(name, zmpp);
		} else {
			zmpp = (ZmppWrapper) getServletContext().getAttribute(name);
		}
		result = zmpp.execute(command);

		return result;
	}

	@Override
	public String getSessionVar(String name) {
		Object o = getThreadLocalRequest().getSession().getAttribute(name);
		if (o != null) {
			return o.toString();
		}
		return "";
	}

	@Override
	public String facebookLogin(String authToken) throws FBException {
		System.out.println("authToken: " + authToken);
		try {
			getHelper().login(authToken);
		} catch (Exception e) {
			if (e.getMessage() == null || e.getMessage().equalsIgnoreCase("redirect!")) {
				throw new FBException("redirect!");
			} else {
				throw new FBException("Login-Fehler 1");
			}
		}
		if (getHelper().getUserID() <= 0) {
			throw new FBException("Login-Fehler 2");
		}
		// _response.sendRedirect("http://www.facebook.com/login.php?v=1.0&api_key=4153a065027a515064a75ccbd317e7f1&next=gzork&canvas=true");
		return "true";
	}

	@Override
	protected void checkPermutationStrongName() throws SecurityException {
		return;
	}
}
